package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.GetTreasureReq;
import com.ydkj.a37e_mall.Classes.Model.Request.TreasureRecordReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetTreasureResp;
import com.ydkj.a37e_mall.Classes.Model.Response.TreasureRecordResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.MyExpandableListView;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/1/16.
 * <p>
 * 我的--》 我的通宝
 */

public class MyTbActivity extends BaseActivity {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private ImageView img_back;
    private TextView tv_mytv_money, tv_mytb_etb, tv_mytb_tb, tv_mytb_no;
    private PullToRefreshScrollView my_tb_ptrscrollview;
    private MyExpandableListView my_mytb_expandablelv;
    private MytbAdapter mytbAdapter;
    public int page;

    private List<TreasureRecordResp.ResultEntity.DataEntity> gtouplist;
    private List<List<TreasureRecordResp.ResultEntity.DataEntity>> childlist;

    private static final int LOAD = 0;// 加载
    private static final int REFRESH = 1;//刷新
    private static final int MORE = 2;// 更多

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_tb);
        mActivity = this;
        init();
        initWindow();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.Af7261b), 0);

    }

    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();

        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_mytv_money = (TextView) mActivity.findViewById(R.id.tv_mytv_money);
        tv_mytb_etb = (TextView) mActivity.findViewById(R.id.tv_mytb_etb);
        tv_mytb_tb = (TextView) mActivity.findViewById(R.id.tv_mytb_tb);
        tv_mytb_no = (TextView) mActivity.findViewById(R.id.tv_mytb_no);
        gtouplist = new ArrayList<>();
        childlist = new ArrayList<>();

        my_tb_ptrscrollview = (PullToRefreshScrollView) mActivity.findViewById(R.id.my_tb_ptrscrollview);
//        my_tb_ptrscrollview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        my_tb_ptrscrollview.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                GetTreasure();
                TreasureRecord(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                TreasureRecord(MORE);
            }
        });

        GetTreasure();
        TreasureRecord(REFRESH);
        my_mytb_expandablelv = (MyExpandableListView) mActivity.findViewById(R.id.my_mytb_expandablelv);
        my_mytb_expandablelv.setGroupIndicator(null);
        my_mytb_expandablelv.setDivider(null);
        mytbAdapter = new MytbAdapter(gtouplist, childlist);
        my_mytb_expandablelv.setAdapter(mytbAdapter);
    }


    private class MytbAdapter extends BaseExpandableListAdapter {
        private List<TreasureRecordResp.ResultEntity.DataEntity> group;
        private List<List<TreasureRecordResp.ResultEntity.DataEntity>> child;


        public MytbAdapter(List<TreasureRecordResp.ResultEntity.DataEntity> group, List<List<TreasureRecordResp.ResultEntity.DataEntity>> child) {

            this.group = group;
            this.child = child;
        }

        @Override
        public int getGroupCount() {
            return group.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return child.get(groupPosition).size();
        }

        @Override
        public TreasureRecordResp.ResultEntity.DataEntity getGroup(int groupPosition) {
            return group.get(groupPosition);
        }

        @Override
        public TreasureRecordResp.ResultEntity.DataEntity getChild(int groupPosition, int childPosition) {
            return child.get(childPosition).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }


        /**
         * 显示：group
         */
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.mytb_group_list, null);
                vh = new ViewHolder();
                vh.img_group = (ImageView) convertView.findViewById(R.id.img_group);
                vh.img_mytb_group_type = (ImageView) convertView.findViewById(R.id.img_mytb_group_type);
                vh.tv_mytb_group_num = (TextView) convertView.findViewById(R.id.tv_mytb_group_num);
                vh.tv_mytb_group_message = (TextView) convertView.findViewById(R.id.tv_mytb_group_message);
                vh.tv_mytb_group_time = (TextView) convertView.findViewById(R.id.tv_mytb_group_time);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            Log.e("ssss", "group===>" + group.size());
            Log.e("ssss", "child===>" + child.size());

            if (getGroup(groupPosition).getTurnover().equals("1")) {
                vh.img_mytb_group_type.setBackground(getResources().getDrawable(R.mipmap.bank_add));
            } else {
                vh.img_mytb_group_type.setBackground(getResources().getDrawable(R.mipmap.bank_rectangle_small));
            }

            vh.tv_mytb_group_message.setText(getGroup(groupPosition).getType());
            vh.tv_mytb_group_num.setText(getGroup(groupPosition).getPrice());
            vh.tv_mytb_group_time.setText(getGroup(groupPosition).getCreated_at());
            //箭头的切换
            if (isExpanded) {
                vh.img_group.setImageResource(R.mipmap.array_up);
            } else {
                vh.img_group.setImageResource(R.mipmap.array_down);
            }
            return convertView;

        }

        /**
         * 显示：child
         */
        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.mytb_child_list, null);
                vh = new ViewHolder();
                vh.tv_mytb_child_order = (TextView) convertView.findViewById(R.id.tv_mytb_child_order);
                vh.tv_mytb_child_type = (TextView) convertView.findViewById(R.id.tv_mytb_child_type);
                vh.tv_mytb_child_store = (TextView) convertView.findViewById(R.id.tv_mytb_child_store);
                vh.tv_mytb_child_adress = (TextView) convertView.findViewById(R.id.tv_mytb_child_adress);
                vh.tv_mytb_child_phone = (TextView) convertView.findViewById(R.id.tv_mytb_child_phone);

                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            vh.tv_mytb_child_order.setText(getChild(groupPosition, childPosition).getSn());
            vh.tv_mytb_child_phone.setText(getChild(groupPosition, childPosition).getMobile());
            vh.tv_mytb_child_adress.setText(getChild(groupPosition, childPosition).getAddress());
            vh.tv_mytb_child_store.setText(getChild(groupPosition, childPosition).getName());
            return convertView;
        }

        private class ViewHolder {
            private ImageView img_group, img_mytb_group_type;
            private TextView tv_mytb_group_num, tv_mytb_group_message, tv_mytb_group_time;
            private TextView tv_mytb_child_order, tv_mytb_child_type, tv_mytb_child_store, tv_mytb_child_adress, tv_mytb_child_phone;

        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }
    }


    //获取我的通宝数量
    private void GetTreasure() {
        CustomProgressDialog.createDialog(mActivity).show();
        GetTreasureReq req = new GetTreasureReq();
        if (myApplication.getDataEntity() == null) {
            return;
        } else {
            req.setUuid(myApplication.getDataEntity().getUuid());
        }
        req.setType("1");

        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                my_tb_ptrscrollview.onRefreshComplete();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("url", "response==" + response);
                if (errno.equals("000")) {
                    GetTreasureResp resp = GsonImpl.get().toObject(response.toString(), GetTreasureResp.class);
                    tv_mytb_etb.setText(resp.getResult().getData().getE_treasure());
                    tv_mytb_tb.setText(resp.getResult().getData().getAlready_treasure());
                    tv_mytb_no.setText(resp.getResult().getData().getUnreleased_treasure());
                    tv_mytv_money.setText(resp.getResult().getData().getTreasure());

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                my_tb_ptrscrollview.onRefreshComplete();
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    //获取会员通宝流水记录
    private void TreasureRecord(final int type) {
        TreasureRecordReq req = new TreasureRecordReq();

        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setType("1");
        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = gtouplist.size() / 10 + 1;
        }
        req.setPage(page + "");
        req.setPage_size("10");
        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
//                CustomProgressDialog.Dismiss();
                my_tb_ptrscrollview.onRefreshComplete();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("ssss", "通宝流水response==" + response);
                if (errno.equals("000")) {
                    TreasureRecordResp resp = GsonImpl.get().toObject(response.toString(), TreasureRecordResp.class);
                    if (type == LOAD || type == REFRESH) {
                        gtouplist.clear();
                        gtouplist.addAll(resp.getResult().getData());
                        for (int i = 0; i < gtouplist.size(); i++) {
                            List<TreasureRecordResp.ResultEntity.DataEntity> list = new ArrayList<TreasureRecordResp.ResultEntity.DataEntity>();
                            list.add(gtouplist.get(i));
                            childlist.add(list);
                        }
                    } else {

                        gtouplist.addAll(resp.getResult().getData());
                        for (int i = 0; i < gtouplist.size(); i++) {
                            List<TreasureRecordResp.ResultEntity.DataEntity> list = new ArrayList<TreasureRecordResp.ResultEntity.DataEntity>();
                            list.add(gtouplist.get(i));
                            childlist.add(list);
                        }
                    }
                    if (gtouplist.size() % 10 > 0) {
                        my_tb_ptrscrollview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        my_tb_ptrscrollview.setMode(PullToRefreshBase.Mode.BOTH);
                    }


                    mytbAdapter.notifyDataSetChanged();
                    my_tb_ptrscrollview.onRefreshComplete();

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }
}
